package api

import (
	"net/http"
	"strconv"

	"gitee.com/h2ob/base"
	"gitee.com/h2ob/facada"
	"gitee.com/h2ob/infra"
	"github.com/gin-gonic/gin"
)

func publishMoment(c *gin.Context) {
	m := &facada.H2oMoment{}
	if err := c.BindJSON(m); err != nil {
		base.GLogger.Infoln("Can not find args")
		c.String(http.StatusBadRequest, "Can not find args")
		return
	}
	uid := c.MustGet(base.HEAD_USER_ID).(string)
	nickName := c.MustGet(base.HEAD_USER_NAME).(string)
	err := infra.AddMoment(uid, nickName, m)
	if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
	} else {
		c.String(http.StatusOK, "OK")
	}
}

func getMoment(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		base.GLogger.Infoln("Can not find args")
		c.Status(http.StatusBadRequest)
		return
	}
	data, err := infra.GetMoment(id)
	if err != nil {
		base.GLogger.Infof("RecommendMoment error:%s", err)
		c.String(http.StatusInternalServerError, err.Error())
		return
	}
	rsp := &facada.H2oRsp{TID: "None", Code: 200, Msg: "OK", Data: data}
	c.JSON(http.StatusOK, rsp)
}

func updateMoment(c *gin.Context) {
	hup := &facada.H2oMomentUpdate{}
	if err := c.BindJSON(hup); err != nil {
		base.GLogger.Infoln("Can not find args")
		c.String(http.StatusBadRequest, "Can not find args")
		return
	}
	err := infra.UpdateMoment(hup)
	if err == nil {
		c.String(http.StatusOK, "OK")
	} else {
		c.String(http.StatusInternalServerError, err.Error())
	}
}

func recommendMoment(c *gin.Context) {
	page := c.Query("page")
	pageSize := c.Query("pageSize")
	if page == "" || pageSize == "" {
		base.GLogger.Infoln("Can not find args")
		c.Status(http.StatusBadRequest)
		return
	}
	pg, _ := strconv.Atoi(page)
	size, _ := strconv.Atoi(pageSize)
	if pg <= 0 || size <= 0 {
		base.GLogger.Infof("page=%s,pageSize=%s:error", page, pageSize)
		c.Status(http.StatusBadRequest)
		return
	}

	hlt, err := infra.RecommendMoment(pg, size)
	if err != nil {
		base.GLogger.Infof("RecommendMoment error:%s", err)
		c.String(http.StatusInternalServerError, err.Error())
		return
	}

	data := make([]*facada.H2oEvent, len(hlt))
	for off := 0; off < len(hlt); off++ {
		it := hlt[off]
		cnt, err := infra.KvGet(infra.MOMENT_TABLE, it.Mid)
		if err != nil {
			base.GLogger.Infof("Get key=%s,error:%s", it.Mid, err)
		}
		data[off] = &facada.H2oEvent{Id: it.Mid, Title: it.Title, Img: it.Img, Tag: it.Tag, Author: it.Author, Time: base.TimeYYYYMM(it.Ctime),
			Views: it.Views, Loves: it.Loves, Location: it.Location, Content: string(cnt)}
	}
	rsp := &facada.H2oRsp{TID: "None", Code: 200, Msg: "OK", Data: data}
	c.JSON(http.StatusOK, rsp)
}
